package com.css.security.browser.authentication;

import com.css.common.core.utils.R;
import com.css.common.security.constant.SecurityConstants;
import com.css.common.security.enums.LoginResponseType;
import com.css.common.security.properties.SecurityProperties;
import com.css.common.security.support.CssUser;
import com.css.common.security.utils.SecurityUtil;
import com.css.lion.optlog.agent.annotation.OptLog;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Security;

/**
 * CssAuthenticationSuccessHandler
 * 浏览器环境下登录成功的配置器
 * @author hanyx
 * @date 2019/04/11
 */
@Slf4j
//@Component("cssAuthenticationSuccessHandler")
public class CssAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private CacheManager cacheManager;

    private RequestCache requestCache = new HttpSessionRequestCache();

    @OptLog(desc = "用户登录", opt = "登录成功")
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");

        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(SecurityUtil.getUser().getUsername()) == null) {
            cache.put(SecurityUtil.getUser().getUsername(), SecurityUtil.getUser());
        }

        // 认证成功后相应方式
        if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())) {
            response.setContentType(SecurityConstants.APPLICATION_JSON_CONTENT_TYPE);
            response.getWriter().write(objectMapper.writeValueAsString(new R(authentication.getPrincipal())));
        } else {
            // 如果设置了css.security.browser.singInSuccessUrl，总是跳到设置的地址上
            // 如果没设置，则尝试跳转到登录之前访问的地址上，如果登录前访问地址为空，则跳到网站根路径上
            if (StringUtils.isNotBlank(securityProperties.getBrowser().getSingInSuccessUrl())) {
                requestCache.removeRequest(request, response);
                setAlwaysUseDefaultTargetUrl(true);
                setDefaultTargetUrl(securityProperties.getBrowser().getSingInSuccessUrl());
            }
            super.onAuthenticationSuccess(request,response,authentication);
        }
    }
}
